from day20.models.models_stu import Stu
from day20.models.models_score import Score
from day20.models.models_emp import Emp
from day20.schema.schema_score import ScoreCreateSchema, ScoreUpdateSchema, ScoreResponseSchema
from day20.database.database import get_db
from day20.crud.crud_score import score_all_info, score_info_by_id, score_add,score_del,score_update
from sqlalchemy.orm import Session
from day20.database.database import Base, engine
from fastapi import Depends, FastAPI, APIRouter, HTTPException
import uvicorn
from typing import Optional

# Base.metadata.create_all(bind=engine)

score_app = APIRouter()


# 获取所有学生的成绩信息
@score_app.get('/score/getall', summary="查询所有成绩信息")
async def get_all_info_score(db: Session = Depends(get_db)):
    return score_all_info(db)

# 获取单个学生的成绩信息
@score_app.get('/score/getone', summary="查询单个学生成绩信息")
async def get_one_info_score(stu_id: int, db: Session = Depends(get_db), assessment_sequence: Optional[int]=None):
    if assessment_sequence != None:
        score1 = score_info_by_id(db=db, stu_id=stu_id, assessment_sequence=assessment_sequence)
        if not score1:
            raise HTTPException(status_code=404, detail="该学生该序次成绩信息不存在")
        return score1
    score2 = score_info_by_id(db, stu_id=stu_id)
    if not score2:
        raise HTTPException(status_code=404, detail="该学生成绩信息不存在")
    return score2


# 添加学生信息
@score_app.post('/score/add', summary="添加学生成绩信息")
async def add_score(score: ScoreCreateSchema, db: Session = Depends(get_db)):
    score1 = score_info_by_id(stu_id=score.stu_id,assessment_sequence=score.assessment_sequence, db=db)
    if score1:
        raise  HTTPException(status_code=404, detail="该学生该序次成绩信息已存在")
    return score_add(db=db, score_schema=score)


# 更新成绩信息
@score_app.put('/score/update', response_model=ScoreResponseSchema, summary="更新学生成绩信息")
async def update_score(stu_id: int,assessment_sequence:int, score_schema: ScoreUpdateSchema, db: Session = Depends(get_db)):
    score1 = score_info_by_id(db=db, stu_id=stu_id, assessment_sequence=assessment_sequence)
    if not score1:
        raise HTTPException(status_code=404, detail="要修改的学生信息不存在！")
        # 传递stu_id参数给更新函数
    return score_update(db=db, stu_id=stu_id, assessment_sequence=assessment_sequence, score_update_schema=score_schema)

# 删除指定学生的信息
@score_app.get('/score/del', summary="删除学生成绩信息")
async def del_score(stu_id: int, db: Session = Depends(get_db)):
    score1 = score_info_by_id(db=db, stu_id=stu_id)
    if not score1:
        raise HTTPException(status_code=404, detail="要删除的学生成绩信息不存在")
    return score_del(db=db, stu_id=stu_id)


# if __name__ == '__main__':
#     uvicorn.run("scores:score_app", host="localhost", port=8000, reload=True)
